package cn.sys.controller;

import cn.sys.entity.StuSecurityQuestionAnswer;
import cn.sys.entity.Student;
import cn.sys.service.StudentService;
import cn.sys.service.impl.StudentServiceImpl;
import cn.sys.util.ParseRequestParameterUtil;
import cn.sys.util.ResponseUtil;
import cn.sys.util.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    private StudentService studentService = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req,
                           HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println(action);

        switch (action){
            case "login":login(req, resp);break;
            case "updatePassword": updatePassword(req, resp);break;
            case "updateStudentInfo": updateStudentInfo(req, resp);break;
            case "getStudentInfo" :getStudentInfo(req, resp); break;

            case "querySecurityQuestion": querySecurityQuestion(req,resp);break;
            case "checkSecurityQuestion":checkSecurityQuestion(req,resp);break;
            case "forgetUpdatePassword" : forgetUpdatePassword(req, resp);break;
            case "getStudentName" : getStudentName(req, resp);break;
            case "findSecurityQuestion" : findSecurityQuestion(req, resp);break;
            case "addMySecurityQuestion" : addMySecurityQuestion(req, resp);break;
        }
    }

    // 添加用户的密保问题，如果密保问题已存在，需要提示修改
    private void addMySecurityQuestion(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("studentInfo");
        if(student == null){
            ResponseUtil.send(resp, ResultData.fail(ResultData.LOGIN_FAIL, "请先登录"));
            return;
        }
        Integer stuId = student.getStuId();
        StuSecurityQuestionAnswer questionAnswer = (StuSecurityQuestionAnswer) ParseRequestParameterUtil.parseRequestParams(req.getParameterMap(), StuSecurityQuestionAnswer.class);
        questionAnswer.setStuId(stuId);
        Date createTime = new Date();
        questionAnswer.setCreateTime(createTime);
        ResultData resultData = studentService.addStuSecurityQuestionAnswer(questionAnswer);
        ResponseUtil.send(resp, resultData);
    }

    // 用户的密保问题，渲染到页面上，前提是用户需要登录
    private void findSecurityQuestion(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("studentInfo");
        if(student == null){
           ResponseUtil.send(resp, ResultData.fail(ResultData.LOGIN_FAIL, "请先登录"));
           return;
        }
        ResultData resultData = studentService.findAllSecurityQuestion();
        ResponseUtil.send(resp, resultData);
    }

    // 用户登录情况下修改密码，需要将用户的账号名渲染到页面上
    private void getStudentName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("studentInfo");
        resp.getWriter().write(student.getStuName());
    }

    // 用户点击忘记密码时，修改密码
    private void forgetUpdatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String newPassword = req.getParameter("newPassword");
        HttpSession session = req.getSession();
        String sessionId = session.getId();
        ResultData resultData = studentService.forgetUpdatePassword(sessionId, newPassword);
        ResponseUtil.send(resp, resultData);
    }

    private void checkSecurityQuestion(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取数据
        HttpSession session = req.getSession();
        String sessionId= session.getId();
        Integer stuId = Integer.valueOf(req.getParameter("stuId"));
        String question = req.getParameter("question");
        String answer = req.getParameter("answer");

        ResultData resultData = studentService.checkAnswer(sessionId, stuId, question, answer);
        ResponseUtil.send(resp, resultData);
    }

    private void querySecurityQuestion(HttpServletRequest req, HttpServletResponse resp) throws  IOException{
        String studentNameOrPhone = req.getParameter("studentNameOrPhone");
        ResultData resultData = studentService.findQuestion(studentNameOrPhone);
        ResponseUtil.send(resp, resultData);
    }

    // 个人信息修改
    private void updateStudentInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 前面已经显示了学生信息，这里直接在页面获取id就可以了
        Integer stuId = Integer.parseInt(req.getParameter("stuId").trim());
        String stuName = req.getParameter("studentName");
        String realName = req.getParameter("realName");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");
        String phoneNum = req.getParameter("phoneNum");
        String schoolName = req.getParameter("schoolName");
        Student student = new Student(stuId, stuName, null, realName, age, gender, phoneNum, schoolName,0,null,null,0);

        ResultData resultData = studentService.updateStudentInfo(student);
        ResponseUtil.send(resp, resultData);
    }

    // 用户进入个人信息修改界面，显示用户信息
    private void getStudentInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取用户信息
        HttpSession session = req.getSession();
        ResultData resultData = new ResultData();
        resultData.put("studentInfo", session.getAttribute("studentInfo"));
        ResponseUtil.send(resp, resultData);
    }

    // 用户在登录情况下修改密码
    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 用户登录过，可以在session中取得用户信息
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("studentInfo");
        String newPassword = req.getParameter("newPassword");
        ResultData resultData = studentService.updatePassword(student.getStuId(), newPassword);

        ResponseUtil.send(resp, resultData);
    }

    private void login(HttpServletRequest req,
                       HttpServletResponse resp) throws IOException {

        /*Student student = (Student)ParseRequestParameterUtil.parseRequestParam(req.getParameterMap(), Student.class);
        System.out.println(student.getStuName()+ "  " + student.getPassword());*/

        String studentName = req.getParameter("studentName");
        String password = req.getParameter("password");
        // 需要先判断账户是否冻结，如果冻结不能登录
        ResultData isLocked = studentService.checkStudentLockState(studentName);
        if((Integer) isLocked.get("code") == ResultData.STUDENT_LOCKED_STATE){
            ResponseUtil.send(resp, isLocked);
            return;
        }

        ResultData resultData = studentService.login(studentName, password);

        //如果用户登录成功，则需要将用户信息存入到session中
        if ( (Integer) resultData.get("code") == ResultData.LOGIN_SUCCESS) {
            HttpSession session = req.getSession();
            session.setAttribute("studentInfo", resultData.get("data"));
            // 用户登录成功，将登录的验证次数置为0，并修改login_time
            Date loginTime = new Date();
            ResultData data = studentService.updateLoginCountAndLoginTime(loginTime, ((Student) resultData.get("data")).getStuId());
            System.out.println(data.get("msg"));
        }else {
            // 用户登录失败，让登录的验证次数加1，如果验证次数>=4（5次）则冻结账户， 注意是根据用户名修改，因为如果登录失败，没有stu_id数据
            ResultData data =  studentService.addLoginCountByName(studentName);
            resultData.put("msg", "登录失败，"+data.get("msg"));
        }

        ResponseUtil.send(resp, resultData);

    }

}
